package com.ch.workmanagerdemo

import android.annotation.SuppressLint
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.util.TimeUtils
import android.view.View
import androidx.annotation.RequiresApi
import androidx.work.*
import java.time.Duration
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    @SuppressLint("InvalidPeriodicWorkRequestInterval")
    @RequiresApi(Build.VERSION_CODES.O)
    fun addWorkManager(view: View) {
        Log.e("Hogan", "点击开始")
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
            .build()
        val data = Data.Builder()
            .putString("data", "Hogan")
            .build()

        //一次性任务
        val workRequest = OneTimeWorkRequest.Builder(MyWork::class.java)
            .setConstraints(constraints)
            .setInitialDelay(5, TimeUnit.SECONDS)
            .setBackoffCriteria(BackoffPolicy.LINEAR, Duration.ofSeconds(5))
            .addTag("chenhu")
            .setInputData(data)
            .build()

        //周期性任务
        val periodicWorkManager =
            PeriodicWorkRequest.Builder(MyWork::class.java, Duration.ofSeconds(5))
                .build()

        val workManager = WorkManager.getInstance(this)
        workManager.enqueue(periodicWorkManager)

        //先执行一个，再执行另一个，组合
        val workContinuation = workManager.beginWith(workRequest)
            .then(workRequest)

        var list: ArrayList<WorkContinuation> = ArrayList<WorkContinuation>()
        list.add(workContinuation)

        //合并操作，比如 先执行AB CD，然后再执行E
        WorkContinuation.combine(list)
            .then(workRequest)
            .enqueue()


        workManager.getWorkInfoByIdLiveData(workRequest.id).observe(this) {
            if (it?.state == WorkInfo.State.SUCCEEDED) {
                val data = it.outputData.getString("data")
                Log.d("Hogan", data.toString())
            }
        }


        Handler().postDelayed(Runnable {
            Log.w("Hogan", "取消Worker")
            //取消Worker
            //   WorkManager.getInstance(this).cancelAllWorkByTag("chenhu")
        }, 3000)


    }
}